package com.quanxiaoha.weblog.web.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quanxiaoha.weblog.common.domain.dos.*;
import com.quanxiaoha.weblog.common.domain.mapper.*;
import com.quanxiaoha.weblog.common.utils.PageResponse;
import com.quanxiaoha.weblog.common.utils.Response;
import com.quanxiaoha.weblog.common.utils.UserContextHolder;
import com.quanxiaoha.weblog.web.model.vo.user.UpdateUserProfileReqVO;
import com.quanxiaoha.weblog.web.model.vo.user.UserPersonalStatsRspVO;
import com.quanxiaoha.weblog.web.model.vo.user.UserProfileRspVO;
import com.quanxiaoha.weblog.web.service.UserProfileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.stream.Collectors;
import java.util.List;

/**
 * 用户个人信息服务实现类
 */
@Service
@Slf4j
public class UserProfileServiceImpl implements UserProfileService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserStatisticsMapper userStatisticsMapper;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private UserFavoriteMapper userFavoriteMapper;
    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private UserContextHolder userContextHolder;

    @Autowired
    private UserLoginLogMapper userLoginLogMapper;

    @Autowired
    private com.quanxiaoha.weblog.admin.service.AdminFileService adminFileService;

    @Override
    public Response getCurrentUserProfile() {
        try {
            Long currentUserId = userContextHolder.getCurrentUserId();
            if (currentUserId == null) {
                return Response.fail("用户未登录");
            }

            return getUserPublicProfile(currentUserId);

        } catch (Exception e) {
            log.error("获取当前用户信息失败", e);
            return Response.fail("获取用户信息失败");
        }
    }

    @Override
    public Response getUserPublicProfile(Long userId) {
        try {
            // 获取用户基本信息
            UserDO user = userMapper.selectById(userId);
            if (user == null) {
                return Response.fail("用户不存在");
            }

            // 获取用户统计数据
            UserStatisticsDO statistics = userStatisticsMapper.selectByUserId(userId);
            if (statistics == null) {
                // 如果统计数据不存在，初始化一个
                initUserStatistics(userId);
                statistics = userStatisticsMapper.selectByUserId(userId);
            }

            // 获取用户角色
            List<UserRoleDO> userRoles = userRoleMapper.selectByUsername(user.getUsername());
            String role = "ROLE_VISITOR"; // 默认角色
            if (!CollectionUtils.isEmpty(userRoles)) {
                role = userRoles.get(0).getRole();
            }

            // 构建返回数据
            UserProfileRspVO profile = UserProfileRspVO.builder()
                    .userId(user.getId())
                    .username(user.getUsername())
                    .nickname(user.getNickname())
                    .avatar(user.getAvatar())
                    .bio(user.getBio())
                    .email(user.getEmail())
                    .emailVerified(user.getEmailVerified())
                    .role(role)
                    .totalArticles(statistics.getTotalArticles())
                    .totalViews(statistics.getTotalViews())
                    .totalLikes(statistics.getTotalLikes())
                    .totalFavorites(statistics.getTotalFavorites())
                    .totalComments(statistics.getTotalComments())
                    .joinTime(user.getCreateTime())
                    .build();

            return Response.success(profile);

        } catch (Exception e) {
            log.error("获取用户公开信息失败", e);
            return Response.fail("获取用户信息失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response updateUserProfile(String nickname, String avatar, String bio) {
        try {
            Long currentUserId = userContextHolder.getCurrentUserId();
            if (currentUserId == null) {
                return Response.fail("用户未登录");
            }

            UserDO user = UserDO.builder()
                    .id(currentUserId)
                    .nickname(nickname)
                    .avatar(avatar)
                    .bio(bio)
                    .updateTime(LocalDateTime.now())
                    .build();

            int result = userMapper.updateById(user);
            if (result > 0) {
                return Response.success("更新成功");
            } else {
                return Response.fail("更新失败");
            }

        } catch (Exception e) {
            log.error("更新用户信息失败", e);
            return Response.fail("更新失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response updateUserProfile(UpdateUserProfileReqVO updateUserProfileReqVO) {
        try {
            Long currentUserId = userContextHolder.getCurrentUserId();
            if (currentUserId == null) {
                return Response.fail("用户未登录");
            }

            int result = userMapper.updateUserProfile(
                    currentUserId,
                    updateUserProfileReqVO.getNickname(),
                    updateUserProfileReqVO.getAvatar(),
                    updateUserProfileReqVO.getBio(),
                    updateUserProfileReqVO.getEmail(),
                    updateUserProfileReqVO.getPhone()
            );

            if (result > 0) {
                return Response.success("更新成功");
            } else {
                return Response.fail("更新失败");
            }

        } catch (Exception e) {
            log.error("更新用户信息失败", e);
            return Response.fail("更新失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response uploadAvatar(org.springframework.web.multipart.MultipartFile file) {
        try {
            Long currentUserId = userContextHolder.getCurrentUserId();
            if (currentUserId == null) {
                return Response.fail("用户未登录");
            }

            // 验证文件类型和大小
            if (file == null || file.isEmpty()) {
                return Response.fail("请选择要上传的文件");
            }
            
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Response.fail("请上传图片文件");
            }
            
            if (file.getSize() > 2 * 1024 * 1024) { // 2MB
                return Response.fail("图片大小不能超过2MB");
            }
            
            // 使用AdminFileService上传头像
            String avatarUrl;
            try {
                Response uploadResult = adminFileService.uploadFile(file);
                if (!uploadResult.isSuccess()) {
                    return Response.fail("头像上传失败");
                }
                
                com.quanxiaoha.weblog.admin.model.vo.file.UploadFileRspVO uploadData = 
                    (com.quanxiaoha.weblog.admin.model.vo.file.UploadFileRspVO) uploadResult.getData();
                avatarUrl = uploadData.getUrl();
                log.info("头像上传成功，URL: {}", avatarUrl);
            } catch (Exception e) {
                log.error("头像上传失败", e);
                return Response.fail("头像上传失败：" + e.getMessage());
            }

            UserDO user = UserDO.builder()
                    .id(currentUserId)
                    .avatar(avatarUrl)
                    .updateTime(LocalDateTime.now())
                    .build();

            int result = userMapper.updateById(user);
            if (result > 0) {
                return Response.success("头像上传成功");
            } else {
                return Response.fail("头像上传失败");
            }

        } catch (Exception e) {
            log.error("头像上传失败", e);
            return Response.fail("头像上传失败");
        }
    }

    @Override
    public Response getUserLoginLogs(Integer page, Integer size) {
        try {
            Long currentUserId = userContextHolder.getCurrentUserId();
            if (currentUserId == null) {
                return Response.fail("用户未登录");
            }

            Page<UserLoginLogDO> pageParam = new Page<>(page, size);
            Page<UserLoginLogDO> result = userLoginLogMapper.selectByUserId(currentUserId, pageParam);

            return PageResponse.success(result, result.getRecords());

        } catch (Exception e) {
            log.error("获取用户登录日志失败", e);
            return Response.fail("获取登录日志失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void initUserStatistics(Long userId) {
        try {
            UserStatisticsDO existingStats = userStatisticsMapper.selectByUserId(userId);
            if (existingStats == null) {
                UserStatisticsDO statistics = UserStatisticsDO.builder()
                        .userId(userId)
                        .totalArticles(0L)
                        .totalViews(0L)
                        .totalLikes(0L)
                        .totalFavorites(0L)
                        .totalComments(0L)
                        .createTime(LocalDateTime.now())
                        .updateTime(LocalDateTime.now())
                        .build();

                userStatisticsMapper.insert(statistics);
                log.info("初始化用户统计数据成功，userId: {}", userId);
            }
        } catch (Exception e) {
            log.error("初始化用户统计数据失败，userId: {}", userId, e);
        }
    }

    @Override
    public Response getUserPersonalStats() {
        try {
            // 获取当前登录用户ID
            Long currentUserId = userContextHolder.getCurrentUserId();
            if (currentUserId == null) {
                return Response.fail("用户未登录");
            }

            // 统计用户发布的文章总数
            Long personalArticleCount = articleMapper.selectCount(Wrappers.<ArticleDO>lambdaQuery()
                    .eq(ArticleDO::getUserId, currentUserId)
                    .eq(ArticleDO::getIsDeleted, false));

            // 统计用户文章的总阅读量
            List<ArticleDO> userArticles = articleMapper.selectList(Wrappers.<ArticleDO>lambdaQuery()
                    .eq(ArticleDO::getUserId, currentUserId)
                    .eq(ArticleDO::getIsDeleted, false)
                    .select(ArticleDO::getId, ArticleDO::getReadNum));
            
            Long personalTotalViews = userArticles.stream()
                    .mapToLong(article -> article.getReadNum() != null ? article.getReadNum() : 0L)
                    .sum();

            // 获取用户文章ID列表
            List<Long> userArticleIds = userArticles.stream()
                    .map(ArticleDO::getId)
                    .collect(Collectors.toList());

            Long personalTotalLikes = 0L;
            Long personalTotalFavorites = 0L;

            if (!CollectionUtils.isEmpty(userArticleIds)) {
                // 统计用户文章的总点赞量（type=1）
                personalTotalLikes = userFavoriteMapper.selectCount(Wrappers.<UserFavoriteDO>lambdaQuery()
                        .in(UserFavoriteDO::getArticleId, userArticleIds)
                        .eq(UserFavoriteDO::getType, 1)
                        .eq(UserFavoriteDO::getIsDeleted, false));

                // 统计用户文章的总收藏量（type=2）
                personalTotalFavorites = userFavoriteMapper.selectCount(Wrappers.<UserFavoriteDO>lambdaQuery()
                        .in(UserFavoriteDO::getArticleId, userArticleIds)
                        .eq(UserFavoriteDO::getType, 2)
                        .eq(UserFavoriteDO::getIsDeleted, false));
            }

            // 统计用户发表的评论总数
            Long personalCommentCount = commentMapper.selectCount(Wrappers.<CommentDO>lambdaQuery()
                    .eq(CommentDO::getUserId, currentUserId)
                    .eq(CommentDO::getIsDeleted, false));

            // 构建响应VO
            UserPersonalStatsRspVO statsVO = UserPersonalStatsRspVO.builder()
                    .personalArticleCount(personalArticleCount)
                    .personalTotalViews(personalTotalViews)
                    .personalTotalLikes(personalTotalLikes)
                    .personalTotalFavorites(personalTotalFavorites)
                    .personalCommentCount(personalCommentCount)
                    .build();

            return Response.success(statsVO);

        } catch (Exception e) {
            log.error("获取用户个人统计信息失败", e);
            return Response.fail("获取统计信息失败");
        }
    }

    @Override
    public Response getUserPersonalPublishStats() {
        try {
            // 获取当前登录用户ID
            Long currentUserId = userContextHolder.getCurrentUserId();
            if (currentUserId == null) {
                return Response.fail("用户未登录");
            }

            // TODO: 实现用户个人文章发布统计逻辑
            // 这里需要根据用户ID统计其文章的发布情况，返回热点图需要的数据格式
            // 暂时返回空数据，后续可以根据具体需求实现
            return Response.success(java.util.Collections.emptyMap());

        } catch (Exception e) {
            log.error("获取用户个人文章发布统计信息失败", e);
            return Response.fail("获取统计信息失败");
        }
    }

    @Override
    public Response getUserPersonalPVStats() {
        try {
            // 获取当前登录用户ID
            Long currentUserId = userContextHolder.getCurrentUserId();
            if (currentUserId == null) {
                return Response.fail("用户未登录");
            }

            // TODO: 实现用户个人PV访问量统计逻辑
            // 这里需要根据用户ID统计其文章的PV访问量情况，返回折线图需要的数据格式
            // 暂时返回空数据，后续可以根据具体需求实现
            return Response.success(java.util.Collections.emptyMap());

        } catch (Exception e) {
            log.error("获取用户个人PV访问量统计信息失败", e);
            return Response.fail("获取统计信息失败");
        }
    }
}
